<template>
  <div class="capability-center">
    <div class="page-header">
      <h2>能力配置中心</h2>
      <a-space>
        <a-button type="primary" @click="openCapabilityMarket">
          能力市场
        </a-button>
        <a-button @click="openCapabilityTemplates"> 能力模板 </a-button>
      </a-space>
    </div>

    <!-- 能力概览 -->
    <a-row :gutter="16" style="margin-bottom: 16px">
      <a-col :span="6">
        <a-card>
          <Statistic
            title="已绑定能力"
            :value="statistics.boundCapabilities"
            :value-style="{ color: '#3f8600' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="可用能力"
            :value="statistics.availableCapabilities"
            :value-style="{ color: '#1890ff' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="能力模板"
            :value="statistics.templates"
            :value-style="{ color: '#722ed1' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="本月使用"
            :value="statistics.monthlyUsage"
            :value-style="{ color: '#cf1322' }"
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 资源能力绑定 -->
    <a-card title="资源能力绑定" style="margin-bottom: 16px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="资源类型">
          <a-select
            v-model:value="searchForm.resourceType"
            placeholder="选择资源类型"
            style="width: 120px"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="entity">实体资源</a-select-option>
            <a-select-option value="service">服务资源</a-select-option>
            <a-select-option value="capability">技术能力</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="能力类型">
          <a-select
            v-model:value="searchForm.capabilityType"
            placeholder="选择能力类型"
            style="width: 120px"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="workflow">工作流</a-select-option>
            <a-select-option value="form">表单</a-select-option>
            <a-select-option value="rule">规则</a-select-option>
            <a-select-option value="report">报表</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset"
            >重置</a-button
          >
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="resourceCapabilities"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'resourceType'">
            <a-tag :color="getResourceTypeColor(record.resourceType)">
              {{ getResourceTypeLabel(record.resourceType) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'capabilityType'">
            <a-tag :color="getCapabilityTypeColor(record.capabilityType)">
              {{ getCapabilityTypeLabel(record.capabilityType) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.enabled ? 'green' : 'red'">
              {{ record.enabled ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="configCapability(record)">配置</a>
              <a @click="toggleCapability(record)">
                {{ record.enabled ? '禁用' : '启用' }}
              </a>
              <a-popconfirm
                title="确定要解绑这个能力吗？"
                @confirm="unbindCapability(record)"
              >
                <a class="text-danger">解绑</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 能力配置模态框 -->
    <a-modal
      v-model:open="configModalVisible"
      title="能力配置"
      width="800px"
      @ok="handleConfigSubmit"
      @cancel="handleConfigCancel"
    >
      <a-form :model="configForm" layout="vertical">
        <a-form-item label="能力名称">
          <a-input v-model:value="configForm.name" disabled />
        </a-form-item>
        <a-form-item label="配置参数">
          <a-textarea
            v-model:value="configForm.config"
            :rows="10"
            placeholder="请输入JSON格式的配置参数"
          />
        </a-form-item>
        <a-form-item label="优先级">
          <a-input-number
            v-model:value="configForm.priority"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 能力市场模态框 -->
    <a-modal
      v-model:open="marketModalVisible"
      title="能力市场"
      width="1200px"
      :footer="null"
    >
      <CapabilityMarket />
    </a-modal>

    <!-- 能力模板模态框 -->
    <a-modal
      v-model:open="templateModalVisible"
      title="能力模板"
      width="1200px"
      :footer="null"
    >
      <CapabilityTemplates />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Statistic } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import {
  getCapabilityInstances,
  getCapabilityTemplates,
} from '#/api/resource-center';

import CapabilityMarket from './components/CapabilityMarket.vue';
import CapabilityTemplates from './components/CapabilityTemplates.vue';

// 响应式数据
const loading = ref(false);
const configModalVisible = ref(false);
const marketModalVisible = ref(false);
const templateModalVisible = ref(false);

const searchForm = reactive({
  resourceType: '',
  capabilityType: '',
});

const configForm = reactive({
  name: '',
  config: '',
  priority: 1,
});

const statistics = ref({
  boundCapabilities: 0,
  availableCapabilities: 0,
  templates: 0,
  monthlyUsage: 0,
});

const resourceCapabilities = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

// 表格列定义
const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
  },
  {
    title: '资源类型',
    dataIndex: 'resourceType',
    key: 'resourceType',
  },
  {
    title: '能力名称',
    dataIndex: 'capabilityName',
    key: 'capabilityName',
  },
  {
    title: '能力类型',
    dataIndex: 'capabilityType',
    key: 'capabilityType',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
  },
  {
    title: '绑定时间',
    dataIndex: 'boundAt',
    key: 'boundAt',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 获取资源类型颜色
const getResourceTypeColor = (type: string) => {
  const colorMap = {
    entity: 'blue',
    service: 'green',
    capability: 'purple',
  };
  return colorMap[type] || 'default';
};

// 获取资源类型标签
const getResourceTypeLabel = (type: string) => {
  const labelMap = {
    entity: '实体资源',
    service: '服务资源',
    capability: '技术能力',
  };
  return labelMap[type] || type;
};

// 获取能力类型颜色
const getCapabilityTypeColor = (type: string) => {
  const colorMap = {
    workflow: 'blue',
    form: 'green',
    rule: 'purple',
    report: 'orange',
    api: 'cyan',
  };
  return colorMap[type] || 'default';
};

// 获取能力类型标签
const getCapabilityTypeLabel = (type: string) => {
  const labelMap = {
    workflow: '工作流',
    form: '表单',
    rule: '规则',
    report: '报表',
    api: 'API',
  };
  return labelMap[type] || type;
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 模拟数据
    statistics.value = {
      boundCapabilities: 45,
      availableCapabilities: 128,
      templates: 32,
      monthlyUsage: 1560,
    };
  } catch (error) {
    message.error('加载统计数据失败');
  }
};

// 加载资源能力列表
const loadResourceCapabilities = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    };

    const result = await getCapabilityInstances(params);
    resourceCapabilities.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    message.error('加载资源能力列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 配置能力
const configCapability = (record: any) => {
  configForm.name = record.capabilityName;
  configForm.config = JSON.stringify({}, null, 2);
  configForm.priority = record.priority;
  configModalVisible.value = true;
};

// 切换能力状态
const toggleCapability = async (record: any) => {
  try {
    await ResourceCapabilityService.toggle(
      record.resourceId,
      record.capabilityId,
      !record.enabled,
    );
    message.success(record.enabled ? '禁用成功' : '启用成功');
    await loadResourceCapabilities();
  } catch (error) {
    message.error('操作失败');
  }
};

// 解绑能力
const unbindCapability = async (record: any) => {
  try {
    await ResourceCapabilityApi.unbind(record.resourceId, record.capabilityId);
    message.success('解绑成功');
    await loadResourceCapabilities();
  } catch (error) {
    message.error('解绑失败');
  }
};

// 提交配置
const handleConfigSubmit = async () => {
  try {
    // 验证JSON格式
    JSON.parse(configForm.config);

    await ResourceCapabilityApi.config({
      resourceId: '1', // 这里应该从当前记录获取
      capabilityId: '1',
      config: JSON.parse(configForm.config),
    });

    message.success('配置成功');
    configModalVisible.value = false;
    await loadResourceCapabilities();
  } catch (error) {
    message.error('配置失败，请检查JSON格式');
  }
};

// 取消配置
const handleConfigCancel = () => {
  configModalVisible.value = false;
};

// 打开能力市场
const openCapabilityMarket = () => {
  marketModalVisible.value = true;
};

// 打开能力模板
const openCapabilityTemplates = () => {
  templateModalVisible.value = true;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadResourceCapabilities();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    resourceType: '',
    capabilityType: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadResourceCapabilities();
};

// 生命周期
onMounted(() => {
  loadStatistics();
  loadResourceCapabilities();
});
</script>

<style lang="less" scoped>
.capability-center {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      margin: 0;
    }
  }

  .text-danger {
    color: #ff4d4f;
  }
}
</style>
